from typing import Optional, List
from pydantic import BaseModel, Field, validator
from datetime import datetime
from app.shared.constants.enums import WorkOrderStatus, WorkOrderPriority, WorkOrderType


class WorkOrderBase(BaseModel):
    """工单基础信息"""
    title: str = Field(..., min_length=1, max_length=200, description="工单标题")
    description: Optional[str] = Field(None, max_length=1000, description="问题描述")
    priority: WorkOrderPriority = Field(..., description="优先级")
    work_order_type: WorkOrderType = Field(..., description="工单类型")
    location: Optional[str] = Field(None, max_length=100, description="位置")
    estimated_duration: Optional[int] = Field(None, ge=1, description="预计处理时长(分钟)")
    required_skills: Optional[List[str]] = Field(None, description="所需技能")
    materials_needed: Optional[List[str]] = Field(None, description="所需物料")


class WorkOrderCreate(WorkOrderBase):
    """创建工单"""
    device_id: int = Field(..., description="设备ID")
    
    @validator('title')
    def validate_title(cls, v):
        if not v.strip():
            raise ValueError('工单标题不能为空')
        return v.strip()


class WorkOrderUpdate(BaseModel):
    """更新工单信息"""
    title: Optional[str] = Field(None, min_length=1, max_length=200, description="工单标题")
    description: Optional[str] = Field(None, max_length=1000, description="问题描述")
    priority: Optional[WorkOrderPriority] = Field(None, description="优先级")
    estimated_duration: Optional[int] = Field(None, ge=1, description="预计处理时长(分钟)")
    required_skills: Optional[List[str]] = Field(None, description="所需技能")
    materials_needed: Optional[List[str]] = Field(None, description="所需物料")


class WorkOrderAssign(BaseModel):
    """工单分配"""
    assignee_id: int = Field(..., description="指派人员ID")
    notes: Optional[str] = Field(None, max_length=500, description="分配备注")
    due_date: Optional[datetime] = Field(None, description="截止时间")


class WorkOrderStatusUpdate(BaseModel):
    """工单状态更新"""
    status: WorkOrderStatus = Field(..., description="工单状态")
    notes: Optional[str] = Field(None, max_length=500, description="状态更新备注")
    completion_notes: Optional[str] = Field(None, max_length=1000, description="完成备注")
    actual_duration: Optional[int] = Field(None, ge=0, description="实际处理时长(分钟)")
    materials_used: Optional[List[str]] = Field(None, description="使用物料")


class WorkOrderResponse(WorkOrderBase):
    """工单响应信息"""
    id: int = Field(..., description="工单ID")
    work_order_number: str = Field(..., description="工单编号")
    device_id: int = Field(..., description="设备ID")
    device_code: Optional[str] = Field(None, description="设备编码")
    device_name: Optional[str] = Field(None, description="设备名称")
    reporter_id: int = Field(..., description="报告人ID")
    reporter_name: Optional[str] = Field(None, description="报告人姓名")
    assignee_id: Optional[int] = Field(None, description="指派人员ID")
    assignee_name: Optional[str] = Field(None, description="指派人员姓名")
    status: WorkOrderStatus = Field(..., description="工单状态")
    created_at: datetime = Field(..., description="创建时间")
    updated_at: datetime = Field(..., description="更新时间")
    assigned_at: Optional[datetime] = Field(None, description="分配时间")
    started_at: Optional[datetime] = Field(None, description="开始处理时间")
    completed_at: Optional[datetime] = Field(None, description="完成时间")
    due_date: Optional[datetime] = Field(None, description="截止时间")
    actual_duration: Optional[int] = Field(None, description="实际处理时长(分钟)")
    completion_notes: Optional[str] = Field(None, description="完成备注")
    
    class Config:
        from_attributes = True


class WorkOrderDetailResponse(WorkOrderResponse):
    """工单详细信息响应"""
    status_history: Optional[List[dict]] = Field(None, description="状态变更历史")
    attachments: Optional[List[dict]] = Field(None, description="附件列表")
    comments: Optional[List[dict]] = Field(None, description="评论列表")


class WorkOrderListQuery(BaseModel):
    """工单列表查询"""
    page: int = Field(1, ge=1, description="页码")
    page_size: int = Field(20, ge=1, le=100, description="每页数量")
    search: Optional[str] = Field(None, description="搜索关键词")
    status: Optional[WorkOrderStatus] = Field(None, description="工单状态筛选")
    priority: Optional[WorkOrderPriority] = Field(None, description="优先级筛选")
    work_order_type: Optional[WorkOrderType] = Field(None, description="工单类型筛选")
    assignee_id: Optional[int] = Field(None, description="指派人员ID筛选")
    reporter_id: Optional[int] = Field(None, description="报告人ID筛选")
    device_id: Optional[int] = Field(None, description="设备ID筛选")
    location: Optional[str] = Field(None, description="位置筛选")
    start_date: Optional[datetime] = Field(None, description="开始日期")
    end_date: Optional[datetime] = Field(None, description="结束日期")
    overdue_only: Optional[bool] = Field(False, description="仅显示过期工单")
    sort_by: Optional[str] = Field("created_at", description="排序字段")
    sort_order: Optional[str] = Field("desc", regex=r'^(asc|desc)$', description="排序方向")


class WorkOrderComment(BaseModel):
    """工单评论"""
    content: str = Field(..., min_length=1, max_length=1000, description="评论内容")
    is_internal: bool = Field(False, description="是否内部评论")


class WorkOrderCommentResponse(BaseModel):
    """工单评论响应"""
    id: int = Field(..., description="评论ID")
    work_order_id: int = Field(..., description="工单ID")
    user_id: int = Field(..., description="评论人ID")
    user_name: str = Field(..., description="评论人姓名")
    content: str = Field(..., description="评论内容")
    is_internal: bool = Field(..., description="是否内部评论")
    created_at: datetime = Field(..., description="创建时间")
    
    class Config:
        from_attributes = True


class WorkOrderAttachment(BaseModel):
    """工单附件"""
    file_name: str = Field(..., description="文件名")
    file_path: str = Field(..., description="文件路径")
    file_size: int = Field(..., description="文件大小")
    file_type: str = Field(..., description="文件类型")


class WorkOrderAttachmentResponse(BaseModel):
    """工单附件响应"""
    id: int = Field(..., description="附件ID")
    work_order_id: int = Field(..., description="工单ID")
    file_name: str = Field(..., description="文件名")
    file_path: str = Field(..., description="文件路径")
    file_size: int = Field(..., description="文件大小")
    file_type: str = Field(..., description="文件类型")
    uploaded_by: int = Field(..., description="上传人ID")
    uploaded_at: datetime = Field(..., description="上传时间")
    
    class Config:
        from_attributes = True


class WorkOrderStatistics(BaseModel):
    """工单统计"""
    total_count: int = Field(..., description="总工单数")
    pending_count: int = Field(..., description="待处理工单数")
    in_progress_count: int = Field(..., description="进行中工单数")
    completed_count: int = Field(..., description="已完成工单数")
    overdue_count: int = Field(..., description="超期工单数")
    avg_resolution_time: Optional[float] = Field(None, description="平均处理时长(小时)")
    completion_rate: float = Field(..., description="完成率")


class WorkOrderBatchOperation(BaseModel):
    """工单批量操作"""
    work_order_ids: List[int] = Field(..., min_items=1, description="工单ID列表")
    operation: str = Field(..., description="操作类型")
    params: Optional[dict] = Field(None, description="操作参数")


class WorkOrderExport(BaseModel):
    """工单导出"""
    format: str = Field("excel", regex=r'^(excel|csv|pdf)$', description="导出格式")
    start_date: Optional[datetime] = Field(None, description="开始日期")
    end_date: Optional[datetime] = Field(None, description="结束日期")
    status: Optional[List[WorkOrderStatus]] = Field(None, description="状态筛选")
    assignee_ids: Optional[List[int]] = Field(None, description="指派人员ID筛选")
    include_comments: bool = Field(False, description="是否包含评论")
    include_attachments: bool = Field(False, description="是否包含附件信息")